package cn.pconline.autoclub.task;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pconline.autoclub.task.util.IdGeneratorByTable;
import cn.pconline.autoclub.task.util.McUtils;


/**
 * 活动旧数据处理任务
 * @author zhoutianhuai
 *
 */
public class ActivityOldDataHandleTask {
  private static Logger log = LoggerFactory.getLogger(ActivityOldDataHandleTask.class);
  /**根据ID查询活动sql**/
  /**根据ID查询活动内容sql**/
  private String getActivityContentByIdSql = "SELECT * from ac_activity_content WHERE activity_id = ?";
  /**保存活动图片sql**/
  private String createActivityPic = "insert into ac_activity_pic(pic_id, activity_id, url, seq, width, height) values (?, ?, ? , ?, ? ,?)";
  /**更新活动内容**/
  private String updateActivityContentSql = "update ac_activity set context = ? ,long_content = ? where activity_id = ?";
  /**删除旧活动内容**/
  private String deleteOldActivityContent = "delete from ac_activity_content where activity_id = ?";
  /**创建活动内容**/
  private String createActivityContent = "insert into ac_activity_content(context_id, activity_id, content, seq) values (?, ?, ? ,?) ON DUPLICATE KEY UPDATE  activity_id = ?, content = ?, seq= ?";
  /**根据clubId查询活动**/
  private String getActivityByClubId = "select * from ac_activity where club_id = ?";
  /**查询所有活动的Id**/
  private String getAllActivity = "select * from ac_activity";
  /**查询活动内容ID**/
  private String getActivityContentIdByActivityId = "select context_id from ac_activity_content where activity_id = ?";
  private static IdGeneratorByTable idGenerator = new IdGeneratorByTable();
  public static void setLog(Logger log) {
	  ActivityOldDataHandleTask.log = log;
  }
  
  public static void main(String[] args) {
	  //初始化Log
      AppUtils.initLog(ActivityOldDataHandleTask.class);
      ActivityOldDataHandleTask t = new ActivityOldDataHandleTask();
      AppUtils.log.info("run activityOldDataHandle start...");
      try {
    	  t.activityOldDataHandleAll();
      } catch (SQLException ex) {
          AppUtils.log.error("activityOldDataHandle fail!", ex);
      }
      AppUtils.log.info("activityOldDataHandle done!");
  }
   
  
  /**
   * 处理所有车友会活动旧数据
   *
   * @param petrolMap
   * @throws SQLException
   */
private void activityOldDataHandleAll() throws SQLException {
      Connection conn = DBUtils.getConnection();
      boolean oldCommit = DBUtils.getAutoCommitValue(conn);
      conn.setAutoCommit(false);
      PreparedStatement ps = null;
      ResultSet rs = null;
      try {
          log.info("---->活动旧数据处理任务---->准备执行……");
          long start = System.currentTimeMillis();
          log.info("---->活动旧数据处理任务---->执行中……");
          //查找所有车友会的活动ID
          ps = conn.prepareStatement(getAllActivity);
          rs = ps.executeQuery();
          while(rs.next()){
        	  oldDataHandle(conn, ps, rs);
          }
          
          long end = System.currentTimeMillis();
          log.info("耗时{}秒", (end - start) / 1000.0);
          log.info("---->活动旧数据处理任务---->执行完毕！");
      } catch (Exception e) {
          log.error("activityOldDataHandle exception!", e);
      } finally {
          conn.commit();
          conn.setAutoCommit(oldCommit);
          DBUtils.releaseConn(conn, ps, rs);
      }

  }

/**
 * 旧数据处理
 * @param conn
 * @param ps
 * @param rs
 * @param isLongContent
 * @param content
 * @param activityId
 * @throws SQLException
 */
private void oldDataHandle(Connection conn, PreparedStatement ps, ResultSet rs) throws SQLException{
	long activityId = rs.getLong("activity_id");
	int isLongContent = rs.getInt("long_content");//内容是否超过255 0--<=255  1-->255
    String content = rs.getString("context");//活动内容
	if(isLongContent == 1){
		  String getActivityContentSql = DBUtils.getSql(getActivityContentByIdSql, "ac_activity_content", activityId);
		  ps = conn.prepareStatement(getActivityContentSql);
		  ps.setLong(1, activityId);
		  rs = ps.executeQuery();
		  while (rs.next()) {
			  content += rs.getString("content");
			        	  
		  }
	 }
	if(!content.equals("")){
		 List<Pictrue> listPicUrl = getPictrueInfo(content);
		 content = content.replaceAll("\\[/img\\]\\r\\n","\\[/img\\]");
		 content = content.replaceAll("\\[(img|img[=\\d,\\d]*)\\](.*?)\\[/img\\]","");//去掉图片url
		 content = content.replaceAll("\\[.+?\\]","");//去掉富文本编辑器符号
		 content = enterTabHandle(content);
		 String activityContent ="";
		 if (content.length() > 255) {
		     activityContent = content.substring(0, 255);
		 }
		 //更新活动内容
		 String newActivityContent = content.length() > 255 ? activityContent : content;
		 int newLongContent = content.length() > 255 ? 1 : 0;
		 ps = conn.prepareStatement(updateActivityContentSql);
		 ps.setString(1, newActivityContent);   
		 ps.setInt(2, newLongContent);
		 ps.setLong(3, activityId);   
		 ps.executeUpdate();
		 //清MC缓存
         McUtils.delete("Activity-" + activityId);
         
		 if(isLongContent == 1){
			 
             String getActivityContentIdByActivity = DBUtils.getSql(getActivityContentIdByActivityId, "ac_activity_content", activityId);
             ps = conn.prepareStatement(getActivityContentIdByActivity);
		     ps.setLong(1, activityId);
		     ps.executeQuery();
		     while(rs.next()){
		    	 //清MC缓存
		         McUtils.delete("ActivityContext-" + rs.getLong("context_id")); 
		     }
             //先删除旧的活动内容
		     String deleteOldActivityContentSql = DBUtils.getSql(deleteOldActivityContent, "ac_activity_content", activityId);
		     ps = conn.prepareStatement(deleteOldActivityContentSql);
		     ps.setLong(1, activityId);
		     ps.executeUpdate();
           
		     String createActivityContentSql = DBUtils.getSql(createActivityContent, "ac_activity_content", activityId);
		     for(int i = 255, n = 1, length = content.length(); i < length; i += 255,n++){
		           int j = Math.min(length, i + 255);
		           ps = conn.prepareStatement(createActivityContentSql);
		           ps.setLong(1, idGenerator.generate("ac_activity_content", "context_id"));
		           ps.setLong(2, activityId);
		           ps.setString(3, content.substring(i, j));
		           ps.setInt(4, n);
		           ps.setLong(5, activityId);
		           ps.setString(6, content.substring(i, j));
		           ps.setInt(7, n);
		           ps.executeUpdate();
		     }
		 }
		             
		 //保存活动图片
		 int seq = 0;
		 for(Pictrue pictrue : listPicUrl){
		        seq++;
			    ps = conn.prepareStatement(createActivityPic);
			    ps.setLong(1, idGenerator.generate("ac_activity_pic", "pic_id"));
		        ps.setLong(2, activityId);
		        if(pictrue.getUrl().length() > 255){
		        	pictrue.setUrl("");
		        }
		        ps.setString(3, pictrue.getUrl());
		        ps.setInt(4, seq);
		        ps.setInt(5, pictrue.getWidth());
		        ps.setInt(6, pictrue.getWidth());
		        ps.executeUpdate();
		  }
		             
		}

}
  /**
   * 正则获得图片信息
   * @param content
   */
  private List<Pictrue> getPictrueInfo(String content){
	  Pattern pattern = Pattern.compile("\\[(img|img[=\\d,\\d]*)\\](.*?)\\[/img\\]");//获取图片正则
	  Matcher matcher = pattern.matcher(content);
	  List<Pictrue> listPicUrl = new ArrayList<Pictrue>();
	  while (matcher.find()) {
		  Pictrue pictrue = new Pictrue();
		  if(matcher.group(1).equals("img")){
			  pictrue.setHeight(0);			  
			  pictrue.setWidth(0);
		  }else{
			  if(matcher.group(1).contains("img=")){
			       String[] arr = matcher.group(1).trim().split("=");
			       String[] wh = arr[1].split(",");
			       pictrue.setWidth(Integer.parseInt(wh[0]));
			       pictrue.setHeight(Integer.parseInt(wh[1]));
			  }
		  }
		 if(!matcher.group(2).equals("")){
			pictrue.setUrl(matcher.group(2).trim());
		 }
		
		 listPicUrl.add(pictrue);
     }
	 return listPicUrl;
  }
  
  /**
   * 连续多个\r\n组合保留一个 连续超过20个不管了
   * 连续多个\n保留一个 超过十个不管了
   * @return
   */
  private String enterTabHandle(String content){
        if(content.startsWith("\r\n")){
        	content = content.substring(2, content.length());
        }
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n\r\n", "\r\n");
	    content = content.replace("\r\n\r\n", "\r\n");
	    content = content.replace("\n\n\n\n\n\n\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n\n\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n\n", "\n");
	    content = content.replace("\n\n\n\n", "\n");
	    content = content.replace("\n\n\n", "\n");
	    content = content.replace("\n\n", "\n");
	    
	    content = content.replace("\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n", "\r\n");
	    content = content.replace("\r\n \r\n \r\n \r\n \r\n \r\n \r\n", "\r\n");
	    content = content.replace("\r\n \r\n \r\n \r\n \r\n \r\n", "\r\n");
	    content = content.replace("\r\n \r\n \r\n \r\n \r\n", "\r\n");
	    content = content.replace("\r\n \r\n \r\n \r\n", "\r\n");
	    content = content.replace("\r\n \r\n \r\n", "\r\n");
	    content = content.replace("\r\n \r\n", "\r\n");
		return content;
  }
}
